from webutils.tornado.web import RequestHandler
from webutils.tornado.responses import Response
from webutils.webargs.tornado import use_args

from message_broker.services import UserService

from message_broker.const import UserGroup
from .. import params


class OnlineUserHandler(RequestHandler):
    @use_args({
        'token': params.Token(required=True),
    }, location='query')
    async def get(self, args, unit_id=None):
        user_service = UserService(self.connection, room_id=unit_id)
        users = await user_service.get_users()
        student_lst = users.get(UserGroup.STUDENT) or []
        teacher_lst = users.get(UserGroup.TEACHER) or []
        data = {
            'total': len(student_lst) + len(teacher_lst),
            'total_student': len(student_lst),
            'total_teacher': len(teacher_lst),
            'list': student_lst + teacher_lst,
        }
        resp = Response(errcode=0, errmsg='ok', data=data)
        self.write_json(resp)
